<template>
  <a-modal
    class="image-cropper"
    v-model:visible="visible"
    title="编辑图片"
    :footer="false"
    @cancel="closeModal"
  >
    <!-- 图片裁切组件 -->
    <vue-cropper
      ref="cropperRef"
      :img="imageUrl"
      output-type="png"
      :info="true"
      :can-move="false"
      :can-move-box="true"
      :fixed-box="false"
      :auto-crop="true"
      :center-box="true"
    />
    <div style="margin-bottom: 16px" />
    <!-- 图片操作 -->
    <div class="image-cropper-action">
      <a-space>
        <a-button @click="rotateLeft">左旋</a-button>
        <a-button @click="rotateRight">右旋</a-button>
        <a-button @click="changeScale(1)">放大</a-button>
        <a-button @click="changeScale(-1)">缩小</a-button>
        <a-button :loading="loading" type="primary" @click="handleConfirm"> 确认</a-button>
      </a-space>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { uploadPictureUsingPost } from '@/api/pictureController'
import { message } from 'ant-design-vue'

interface Props {
  imageUrl?: string
  picture?: API.PictureVO
  spaceId?: number
  onSuccess?: (newPicture: API.PictureVO) => void
}

const props = defineProps<Props>()

// 获取图片裁切器的引用
const cropperRef = ref()

const changeScale = (num) => {
  num = num || 1
  cropperRef?.value.changeScale(num)
}
const rotateLeft = () => {
  cropperRef?.value.rotateLeft()
}
const rotateRight = () => {
  cropperRef?.value.rotateRight()
}

const handleConfirm = () => {
  cropperRef?.value.getCropBlob((blob: Blob) => {
    const filename = (props.picture?.name || 'picture') + '.png'
    const file = new File([blob], filename, { type: blob.type })
    handleUpload({ file })
  })
}
const loading = ref(false)

const handleUpload = async ({ file }: any) => {
  loading.value = true
  try {
    const params: API.PictureUploadRequest = props.picture ? { id: props.picture.id } : {}
    params.spaceId = props.spaceId
    const res = await uploadPictureUsingPost(params, {}, file)
    if (res.data.code === 0 && res.data.data) {
      message.success('图片上传成功')
      console.log('上传成功, ', res.data.data)
      // 将上传成功的图片信息传递给父组件
      props.onSuccess?.(res.data.data)
      closeModal()
    } else {
      message.error('图片上传失败: ' + res.data.message)
    }
  } catch (error) {
    console.log('图片上传失败, ', error)
    message.error('图片上传失败,' + error)
  }
  loading.value = false
}

const visible = ref(false)

const openModal = () => {
  visible.value = true
}
const closeModal = () => {
  visible.value = false
}

defineExpose({
  openModal,
})
</script>

<style>
.image-cropper {
  text-align: center;
}

.image-cropper .vue-cropper {
  height: 400px !important;
}
</style>
